﻿//***********************************************************************
// Assembly         : phpmk
// Author           : 
// Created          : 04-02-2010
//
// Last Modified By : 
// Last Modified On : 04-03-2010
// Description      : 
//
// Copyright        : (c) Another-D-Mention Software. All rights reserved.
//***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace phpmk.ADM.Utils {
    internal sealed class WebUtil {
        
        public static string PostToUrl(string sUrl, string sData) {
            return PostToUrl(sUrl, sData, 3000);
        }

        public static string PostToUrl(string sUrl, string sData, int timeOut) {
            try {
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(sUrl);
                httpReq.Method = "POST";
                httpReq.ContentType = "application/x-www-form-urlencoded";
                httpReq.ContentLength = sData.Length;
                httpReq.Timeout = timeOut;

                Stream st = httpReq.GetRequestStream();
                StreamWriter stw = new StreamWriter(st);
                stw.Write(sData);

                stw.Flush();
                stw.Close();

                HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
                if (httpRes.StatusCode == HttpStatusCode.OK) {
                    StreamReader sr = new StreamReader(httpRes.GetResponseStream());
                    string result = sr.ReadToEnd();
                    sr.Close();

                    return result;
                } else {
                    throw new ResponseException("FAILED");
                }
            } catch (Exception ex) {
                Debug.Log(ex.Message);
                throw new ResponseException("FAILED");
            }
        }
    }

    [Serializable]
    public sealed class ResponseException : Exception {
        public ResponseException(string message) : base(message) {
        }
    }
}
